package app;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.HandlerUtil;
import com.lidroid.xutils.util.LogUtils;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import model.LoginUser;


public class Login extends AppActivity {

    TextView AppDesc;

    ImageView AppIconBackground;

    ImageView AppIconTitle;

    EditText editTextUser;

    EditText editTextPwd;

    Button buttonLogin;

    Button buttonEdit;

    CheckBox checkBox;

    LoginUser userDB;

    //    private final String url = "http://192.168.3.67:8081";
//   private final String url = "http://221.228.242.3:8060";
//   private final String url2 = "http://221.228.242.3:8061";
//    private final String url = "http://162.20.9.152:8060";
//    private final String url2 = "http://162.20.9.152:8061";
//    private final String url = "http://192.168.3.67:8081";
//    private final String url2 = "http://192.168.3.67:8081";
//    private final String url = "http://xwoa.ngrok.xiaotushuo.com:8000";
//    private final String url2 = "http://xwoa.ngrok.xiaotushuo.com:8000";
//    private final String url = "http://221.228.242.3:8060";
//    private final String url2 = "http://221.228.242.3:8060";
//    private final String url = "http://localhost:8081";
//    private final String url2 = "http://localhost:8081"
//    http://show.ixinwu.com
//    http://news.ixinwu.com
    private final String url = "http://162.20.9.152:8060";
    private final String url2 = "http://162.20.9.152:8061";
//    private final String url = "http://xwoa.ngrok.xiaotushuo.com/";
//    private final String url2 = "http://xwoa.ngrok.xiaotushuo.com/";
//    private final String url = "http://101.132.195.226:8062/";
//    private final String url2 = "http://101.132.195.226:8062/";
//    private final String url = "http://show.ixinwu.com";
//    private final String url2 = "http://show.ixinwu.com";
//    private final String url = "http://192.168.3.54:8081";
//    private final String url2 = "http://192.168.3.54:8081";
//    private final String url = "http://show.ixinwu.com";
//    private final String url2 = "http://news.ixinwu.com";

//    private final String url = "http://172.16.0.211:8080";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        setLoadingView(R.layout.loading_round);
        //先不运行signalr连接服务
        setRunSignalrService(false);
        super.onCreate(savedInstanceState);

        //
        setContentView(R.layout.login);
        setStatusBarVisible(View.GONE);
        AppDesc = (TextView) findViewById(R.id.AppDesc);
        AppIconBackground = (ImageView) findViewById(R.id.AppIconBackground);
        AppIconTitle = (ImageView) findViewById(R.id.AppIconTitle);
        editTextUser = (EditText) findViewById(R.id.editTextUser);
        editTextPwd = (EditText) findViewById(R.id.editTextPwd);
        buttonLogin = (Button) findViewById(R.id.login);
        buttonLogin.setEnabled(true);
        buttonEdit = (Button) findViewById(R.id.buttonEdit);
        checkBox = (CheckBox) findViewById(R.id.checkBox);

        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
        buttonEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openEditIP();
            }
        });


        setTitleDisplay(false);

        try {
            userDB = getDB().findFirst(LoginUser.class);
        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

//        initImage();

        if (userDB != null && userDB.autoLogin) {
            editTextUser.setText(userDB.userName);
            editTextPwd.setText(userDB.pwd);
            checkBox.setChecked(userDB.autoLogin);
            login();
        }


        AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppIPUrl, url);
        HttpUrlConstant.setWebSite(url);
        HttpUrlConstant.setWebSite2(url2);

    }

    void login() {
        editTextUser.setError(null);
        editTextPwd.setError(null);

        if (Check.isEmpty(editTextUser.getText().toString())) {
            editTextUser.setError("不能为空");
            return;
        }
//        else if(Check.isEmpty(editTextPwd.getText().toString()) && !editTextUser.getText().toString().equalsIgnoreCase("admin")){
//            editTextPwd.setError("不能为空");
//        }
        else {
            String userName = editTextUser.getText().toString();
            String pwd = editTextPwd.getText().toString();

            buttonLogin.setEnabled(false);
            buttonLogin.setText("登陆中请稍后");
            //登陆
            Login(userName, pwd, new IReturnObject<Boolean>() {
                @Override
                public void returnResult(Boolean result) {
                    if (result) {
                        buttonLogin.setEnabled(false);
                        buttonLogin.setText("登陆成功");
                    } else {
                        buttonLogin.setEnabled(true);
                        buttonLogin.setText("重试");
                    }

                    if (result) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                //保存ip
                                try {

                                } catch (Exception e) {
                                    LogUtils.e(e.getMessage() + "");
                                }
                                //保存身份
                                boolean isCheck = checkBox.isChecked();
                                try {

                                    LoginUser user = AppApplication.getUser();
                                    if (user != null) {
                                        user.userName = editTextUser.getText().toString();
                                        user.pwd = editTextPwd.getText().toString();
                                        user.autoLogin = isCheck;
                                        getDB().update(user);
                                    } else {
                                        user = new LoginUser();
                                        user.userName = editTextUser.getText().toString();
                                        user.pwd = editTextPwd.getText().toString();
                                        user.autoLogin = isCheck;
                                        getDB().save(user);
                                    }
                                    AppApplication.setUser(user);
                                    //设置别名
                                    AppApplication.getInstance().setNotification();
                                    AppApplication.getInstance().setAlias(user.EmplID);
                                } catch (Exception e) {
                                    LogUtils.e(e.getMessage() + "");
                                }
                                HandlerUtil.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        hideAll();

                                        //打开udp推送服务
//                                        startUDPPushService(AppApplication.getUser().userName,1,"218.246.33.59","9966");
//                                        startUDPPushService(AndroidUtil.getUniqueID(Login.this),1,"218.246.33.59","9966");

                                        startActivity(new Intent(Login.this, Main.class));
                                        overridePendingTransition(com.example.menhoo.menhoolibrary.R.anim.anim_scale_in, com
                                                .example.menhoo.menhoolibrary.R
                                                .anim.anim_scale_out);
                                        onBackPressed();
                                    }
                                });


                            }
                        }).start();


                    } else {
                        HandlerUtil.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                hideAll();
//                                showSimpleDialogMessage("登陆失败", true);
                            }
                        });

                    }
                }
            });
        }
    }

//    void initImage(){
//        try {
//            AppDesc.setText(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppDesc));
//            AppDesc.setText(R.string.app_name);
//            AppIconTitle.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(this.getResources()
//                    .openRawResource(R.raw.app_icon_title)), 15f));

//            AppDesc.setText(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppDesc));

//            String AppIconTitleVal = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIconTitle);
//            String AppIconBackgroundVal = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIconBackground);
//
//            if(AppIconTitleVal.equalsIgnoreCase("app_icon_title.png")){
//                AppIconTitle.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(this.getResources()
//                        .openRawResource(R.raw.app_icon_title)), 15f));
//            }
//            else{
//                getIconLoader().display(AppIconTitle,HttpUrlConstant.getWebSiteFullUrl(AppIconTitleVal));
//            }
//            if(AppIconBackgroundVal.equalsIgnoreCase("app_icon_background.png")){
//                AppIconBackground.setImageBitmap(BitmapFactory.decodeStream(this.getResources().openRawResource(R.raw.app_icon_background)));
//            }
//            else{
//                getIconLoader().display(AppIconBackground,HttpUrlConstant.getWebSiteFullUrl(AppIconBackgroundVal));
//            }
//        } catch (Exception e) {
//            LogUtils.e(e.getMessage() + "");
//        }
//    }


    void openEditIP() {
        final android.app.Dialog dialog = showSimpleCustomDialogMessage(R.layout.custom_dialog, false);
        if (dialog != null) {
            final android.widget.EditText editText = (android.widget.EditText) dialog.findViewById(R.id.editText);
            final String lishi_ip = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIPUrl);
            if (!Check.isEmpty(lishi_ip)) {
                editText.setText(lishi_ip);
                editText.selectAll();
            }
            //
            Button buttonOk = (Button) dialog.findViewById(R.id.buttonOk);
            buttonOk.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String newIP = editText.getText().toString();
                    if (!Check.isEmpty(newIP)) {
                        newIP = newIP.replace("http://", "").replace("https://", "");
                        final String https = "https://" + newIP;
                        final String http = "http://" + newIP;
                        showLoading();

                        Network.isNetworkAvailable(Login.this, https, new com.example.menhoo.toollibrary.android.async.IReturnObject<Boolean>() {


                            @Override
                            public void returnResult(Boolean result) {
                                if (result) {
                                    MessageUtil.showShortToast(Login.this, "服务器地址设置成功！ 当前模式 https");
                                    hideAll();
                                    AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppIPUrl, https);
                                    HttpUrlConstant.setWebSite(https);
                                    InitImageValue();
                                } else {
                                    Network.isNetworkAvailable(Login.this, http, new com.example.menhoo.toollibrary.android.async.IReturnObject<Boolean>() {


                                        @Override
                                        public void returnResult(Boolean result) {
                                            if (result) {
                                                MessageUtil.showShortToast(Login.this, "服务器地址设置成功！ 当前模式 http");
                                                hideAll();
                                                AppApplication.getAppKeyValueSet().writeAppSetPreferences(KeyConstant.AppIPUrl,
                                                        http);
                                                HttpUrlConstant.setWebSite(http);
                                                InitImageValue();
                                            } else {
                                                MessageUtil.showLongToast(Login.this, "服务器地址设置失败，请检查地址是否正确，或者当前网络是否通畅。");
                                                hideAll();
                                                openEditIP();
                                            }
                                        }
                                    });
                                }
                            }
                        });
                        dialog.dismiss();
                    } else {
                        MessageUtil.showShortToast(Login.this, "服务器地址不能为空");
                    }
                }
            });
            //
            Button buttonCancel = (Button) dialog.findViewById(R.id.buttonCancel);
            buttonCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
    }

    void InitImageValue() {
        SplashScreen.InitImageValue(new IReturnObject() {
            @Override
            public void returnResult(Object result) {
//                initImage();
            }
        });
    }

}
